package top.stmo;


import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *      ------------------------响应Response字符数据-------------------------
 *
 *      PrintWriter writer = resp.getWriter()    通过Response对象获取字符输出流
 *      writer.write("aaa")                      通过字符输出流写数据
 *
 *      //content-type，告诉浏览器返回的数据类型是HTML类型数据，这样浏览器才会解析HTML标签
 *      resp.setHeader("content-type","text/html");
 *
 *      //设置响应的数据格式及数据的编码
 *      response.setContentType("text/html;charset=utf-8");
 *      writer.write("你好");
 *
 *      注意:一次请求响应结束后，response对象就会被销毁掉，所以不要手动关闭流
 *
 *      ------------------------响应Response字节数据-------------------------
 *
 *      ServletOutputStream outputStream =resp.getOutputStream()  通过Response对象获取字节输出流
 *      outputStream.write(字节数据)                                通过字节输出流写数据
 *
 *      使用commons-io依赖下工具类完成io流的循环复制
 *
 */
@WebServlet("/rsp4")
public class Response4 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                                            throws ServletException, IOException {

        File file = new File("ttt.png");
        FileInputStream fis = new FileInputStream(file);
        ServletOutputStream outputStream = resp.getOutputStream();

//        int len;
//        byte[] bytes = new byte[10];
//        while ((len = fis.read(bytes)) != -1) {
//            outputStream.write(bytes,0,len);
//        }
        //使用工具类完成io流的循环复制
        IOUtils.copy(fis,outputStream);

        fis.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                                            throws ServletException, IOException {
        doGet(req,resp);
    }
}
